<template>
  <view class="form-content">
    <u-form
      :model="form"
      ref="refForm"
      label-position="top"
      :error-type="['toast']"
    >
      <u-form-item label="研究名称" prop="expName" :required="true">
        <view class="white-bg">
          <u-input v-model="form.expName" />
        </view>
      </u-form-item>
      <u-form-item label="研究分期" prop="stagesList" :required="true">
        <view class="white-bg">
          <ld-select
            :multiple="true"
            :list="seleceList['stagesList']"
            label-key="name"
            value-key="dictDataId"
            placeholder="请选择"
            clearable
            v-model="form.stagesList"
            @change="(val:any)=>selectChange(val,'stagesList')"
          ></ld-select>
        </view>
      </u-form-item>
      <u-form-item label="人员角色" prop="roleList" :required="true">
        <view class="white-bg">
          <ld-select
            :multiple="true"
            :list="seleceList['roleList']"
            label-key="name"
            value-key="dictDataId"
            placeholder="请选择"
            clearable
            v-model="form.roleList"
            @change="(val:any)=>selectChange(val,'roleList')"
          ></ld-select>
        </view>
      </u-form-item>
      <u-form-item label="是否主研" prop="mainFlag" :required="true">
        <view class="white-bg">
          <u-input
            v-model="form.mainFlagName"
            type="select"
            @click="showSelect('mainFlag')"
          />
        </view>
      </u-form-item>
      <u-form-item label="参与项目开始时间" prop="startDate" :required="true">
        <view class="white-bg">
          <u-input
            v-model="form.startDate"
            type="select"
            @click="showSelect('startDate')"
          />
        </view>
      </u-form-item>
      <u-form-item label="参与项目结束时间" prop="endDate" :required="true">
        <view class="white-bg">
          <u-input
            v-model="form.endDate"
            type="select"
            @click="showSelect('endDate')"
          />
        </view>
      </u-form-item>
    </u-form>
  </view>
  <!--编辑选择型字段-->
  <editSelectFeildVue
    ref="refEditSelectFeildVue"
    :info="form"
    @submit="submit"
  />
</template>
<script lang="ts" setup>
import { regExpLiteral } from '@babel/types';
import editSelectFeildVue from '../editSelectFeild.vue';
import { getDictdata } from '@/api/modules/user';
import { onReady } from '@dcloudio/uni-app';
import { getEchoValue, getValueIndex } from '../../index';
import IdSelect from '@/components/ld-select/ld-select.vue';

const props = withDefaults(
  defineProps<{
    form: any;
  }>(),
  {
    form: {
      expName: '',
      stagesList: [],
      roleList: [],
      mainFlag: 1,
      mainFlagName: '是',
      startDate: '',
      endDate: '',
    },
  }
);

const form = ref<any>({
  stagesList: [],
  roleList: [],
});

watch(
  () => props.form,
  (nVal) => {
    form.value = nVal;
  },
  {
    deep: true,
  }
);

const refForm = ref();
const seleceList = ref<any>({
  mainFlag: [
    {
      label: '是',
      value: 1,
    },
    {
      label: '否',
      value: 0,
    },
  ],
});
const selectChange = (val: any, feild: string) => {
  console.log(val);
  form.value[feild] = val;
};
const rules = {
  expName: [
    {
      required: true,
      message: '请输入研究名称',
      trigger: 'blur,change',
    },
  ],
  stagesList: [
    {
      required: true,
      type: 'array',
      message: '请选择研究分期',
      trigger: 'change',
    },
  ],
  roleList: [
    {
      required: true,
      type: 'array',
      message: '请选择人员角色',
      trigger: 'change',
    },
  ],
  startDate: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
    },
  ],
  endDate: [
    {
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
    },
  ],
};

const submit = (data: any) => {
  data.mainFlagName = getEchoValue(
    form.value.mainFlag,
    seleceList.value.mainFlag
  );
  form.value = data;
  console.log(data);
};
const getData = () => {
  return new Promise((resolve, reject) => {
    refForm.value.validate((valid: boolean) => {
      if (valid) {
        if (
          form.value.startDate &&
          form.value.endDate &&
          new Date(form.value.startDate) > new Date(form.value.endDate)
        ) {
          uni.showToast({
            title: '开始时间不能大于结束时间',
            icon: 'none',
            duration: 2000,
          });
          return reject(false);
        }
        if (form.value.stagesList) {
          form.value.stagesIds = form.value.stagesList.join(',');
          const stageArr: string[] = [];
          form.value.stagesList.forEach((item: any) => {
            const newArr = seleceList.value.stagesList.filter(
              (ele: any) => ele.dictDataId === item
            );
            if (newArr.length) {
              stageArr.push(newArr[0].name);
            }
          });
          form.value.stages = stageArr.join(',');
        }
        if (form.value.roleList) {
          form.value.roleIds = form.value.roleList.join(',');
          const roleArr: string[] = [];
          form.value.roleList.forEach((item: any) => {
            const newArr = seleceList.value.roleList.filter(
              (ele: any) => ele.dictDataId === item
            );
            if (newArr.length) {
              roleArr.push(newArr[0].name);
            }
          });
          form.value.roleNames = roleArr.join(',');
        }
        return resolve(form.value);
      } else {
        return reject(false);
      }
    });
  });
};

const refEditSelectFeildVue = ref();
const showSelect = (feild: string) => {
  if (['startDate', 'endDate'].includes(feild)) {
    refEditSelectFeildVue.value.showSelect(
      [],
      feild,
      'picker',
      form.value[feild]
    );
  } else {
    let props = undefined;
    if (['stagesList', 'roleList'].includes(feild)) {
      props = { value: 'dictDataId', label: 'name' };
    }
    let defaultValue = [];
    if (form.value[feild]) {
      defaultValue = seleceList.value[feild].findIndex(
        (el: any) => el.dictDataId === form.value[feild]
      );
    }
    refEditSelectFeildVue.value.showSelect(
      seleceList.value[feild],
      feild,
      'select',
      defaultValue,
      props
    );
  }
};

onMounted(() => {
  seleceList.value.stagesList = [];
  seleceList.value.roleList = [];
  getDictdata({ flag: 'TRIAL_STAGES,PERSON_ROLE' })
    .then((res: any) => {
      seleceList.value.stagesList = res.TRIAL_STAGES;
      seleceList.value.roleList = res.PERSON_ROLE;
    })
    .catch(() => {});
});

onReady(() => {
  refForm.value.setRules(rules);
});

defineExpose({
  getData,
});
</script>
<style lang="scss">
.form-content {
  padding: 32rpx;
  .white-bg {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 20rpx;
  }
}
</style>
